package com.sgb.kjwl.view.ui.fragment.material;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.amap.api.maps.MapView;
import com.sgb.alimaplibrary.MapMarkerTools;
import com.sgb.alimaplibrary.util.ToastUtil;
import com.sgb.kjwl.AppFragment;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.FragmentSupplierBinding;
import com.sgb.kjwl.di.home.DaggerHomeFragComponent;
import com.sgb.kjwl.di.home.HomeFragModule;
import com.swgk.core.view.entity.MenuEntity;
import com.swgk.core.util.PickSelectEntity;
import com.sgb.kjwl.model.entity.supplier3.DictEntity3;
import com.sgb.kjwl.model.entity.supplier3.SupplierRecommendEntity;
import com.sgb.alimaplibrary.SelectAddressActivity;
import com.sgb.kjwl.view.ui.activity.manage.ShopInfoForCompanyTradesActivity;
import com.sgb.kjwl.view.ui.adapter.supplier3.SupplierRecommendAdapter;
import com.sgb.kjwl.view.widget.DictWindow3;
import com.sgb.kjwl.view.widget.EnterprisePopWindow;
import com.sgb.kjwl.view.widget.MapInfoDialog4;
import com.sgb.kjwl.view.widget.MapInfoWindow4;
import com.sgb.kjwl.view.widget.MultiWindow3;
import com.sgb.kjwl.viewmodel.supplier3.SupplierFrgModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.dialog.BasePopWindow;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.xrecyclerview.XRecyclerView;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

public class SupplierFragment extends AppFragment {
    public static final String TYPE_LIST = "列表";
    public static final String TYPE_MAP = "图查";
    private FragmentSupplierBinding binding;
    private SupplierRecommendAdapter supplierRecommendAdapter;
    private DictWindow3 supplierCityWindow3;
    private DictWindow3 supplierSortWindow3;
    private MultiWindow3 supplierTypeWindow3;
    @Inject
    SupplierFrgModel viewModel;

    private Double currentLat;
    private Double currentLong;
    private List<SupplierRecommendEntity> mapSupplierList;
    private Map conditionMap;
    private Map conditionList;
    private List<DictEntity3> cityDictEntityList;
    private EditText searchText;

    private boolean isCreate = false;
    private boolean init = true;
    private boolean isVisible;
    private boolean isMap;
    private MapMarkerTools mapMarkerTools;
    List<SupplierRecommendEntity> bundles = new ArrayList<>();

    private List<MenuEntity> goodsType;
    private List<PickSelectEntity> typeDatas = new ArrayList<>();
    private EnterprisePopWindow pickTypePopWindow;

    private List<PickSelectEntity> distanceDatas = new ArrayList<>();
    private EnterprisePopWindow pickDistancePopWindow;

    private String categoryName = "";
    private String distance = "";
    private String distanceTemp="";

    public static SupplierFragment newInstance(boolean isMap, List<MenuEntity> goodsType) {
        SupplierFragment fragment = new SupplierFragment();
        Bundle bundle = new Bundle();
        bundle.putBoolean("isMap", isMap);
        bundle.putSerializable("goodsType", (Serializable) goodsType);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        isVisible = isVisibleToUser;
        if (!isCreate) {
            return;
        }
        if (isVisibleToUser) {
            if (init) {
                init = false;
                initView();
                init();
            }
        }
    }

    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
        DaggerHomeFragComponent.builder()
                .appComponent(appComponent)
                .homeFragModule(new HomeFragModule(this))
                .build()
                .inject(this);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        isCreate = true;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_supplier, container, false);
        mapMarkerTools = new MapMarkerTools(getActivity(), getLifecycle());
        initMap(savedInstanceState);
        return binding.getRoot();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (init && isVisible) {
            init = false;
            initView();
            init();
        }
    }

    private void initView() {
        binding.setViewModel(viewModel);
        isMap = getArguments().getBoolean("isMap", false);
        goodsType = (List<MenuEntity>) getArguments().getSerializable("goodsType");
        setSecondTypeDatas(goodsType);
        initPopWindow();
        searchText = binding.titleView;
        binding.searchTv.setOnClickListener(this);
        binding.rightView.setOnClickListener(this);
        binding.rightViewLocation.setOnClickListener(this);
        binding.tvType.setOnClickListener(this);
        binding.tvDistance.setOnClickListener(this);
        binding.imgBackTop.setOnClickListener(this);

        if (supplierRecommendAdapter == null) {
            supplierRecommendAdapter = new SupplierRecommendAdapter(getActivity(), null);
        }
        if (isMap) {
            binding.rightView.setText(TYPE_LIST);
            binding.listLayout.setVisibility(View.GONE);
            binding.mapView.setVisibility(View.VISIBLE);
            binding.rightViewLocation.setVisibility(View.VISIBLE);
            //binding.sortView.setVisibility(View.GONE);
        } else {
            binding.rightView.setText(TYPE_MAP);
            binding.listLayout.setVisibility(View.VISIBLE);
            binding.mapView.setVisibility(View.GONE);
            binding.rightViewLocation.setVisibility(View.VISIBLE);
            //binding.sortView.setVisibility(View.VISIBLE);
        }

       /* if (intMap != 0) {//地图模式下文字显示为列表,显示定位按钮
            binding.rightView.setText(TYPE_LIST);
            binding.listLayout.setVisibility(View.GONE);
            binding.mapView.setVisibility(View.VISIBLE);
            //binding.sortView.setVisibility(View.GONE);
            binding.rightViewLocation.setVisibility(View.VISIBLE);
            binding.vLine.setVisibility(View.VISIBLE);
            binding.rightView.setText(TYPE_LIST);
        } else {//列表模式下文字显示为地图,隐藏定位按钮
            //binding.sortView.setVisibility(View.VISIBLE);
            binding.rightViewLocation.setVisibility(View.VISIBLE);
            binding.vLine.setVisibility(View.GONE);
            binding.rightView.setText(TYPE_MAP);
            Map map = new HashMap();
            map.put("latitude", currentLat);
            map.put("longitude", currentLong);
            Log.e("tagmapaddress", map.toString());
            viewModel.getSupplierListModel(map, false);
        }*/
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        binding.rlvList.setLayoutManager(layoutManager);
        binding.rlvList.setAdapter(supplierRecommendAdapter);

        binding.rlvList.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (layoutManager.findFirstVisibleItemPosition() > 1) {
                    binding.imgBackTop.setVisibility(View.VISIBLE);
                } else {
                    binding.imgBackTop.setVisibility(View.GONE);
                }
            }
        });
        supplierRecommendAdapter.setOnItemClick(new AdapterOnItemClick<SupplierRecommendEntity>() {
            @Override
            public void onItemClick(SupplierRecommendEntity supplierRecommendEntity, int position) {
                if (TextUtils.isEmpty(supplierRecommendEntity.getCompanyId())) {
                    ToastUtil.show(getContext(), "企业店铺id不能为空");
                    return;
                }
                ShopInfoForCompanyTradesActivity.startAct(getActivity(), supplierRecommendEntity.getCompanyId(), "", 0, 0);

            }
        });

        binding.rlvList.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
//                Map map = new HashMap();
//                map.put("latitude", currentLat);
//                map.put("longitude", currentLong);
//                Log.e("tagmapaddress", map.toString());
                viewModel.getSupplierListModel(conditionList, false);
            }

            @Override
            public void onLoadMore() {
//                Map map = new HashMap();
//                map.put("latitude", currentLat);
//                map.put("longitude", currentLong);
                viewModel.getSupplierListModel(conditionList, true);
            }
        });

        // 商品分类
        pickTypePopWindow = new EnterprisePopWindow(getActivity());
        pickTypePopWindow.setBgView(binding.grayLayout);
        pickTypePopWindow.setOnResultClick(new BasePopWindow.OnResultClick() {
            @Override
            public void result(Object key1, Object key2, Object key3) {
                categoryName = (String) key2;
                if ("全部".equals(categoryName)) {
                    conditionList.put("categoryName", "");
                    conditionMap.put("categoryName", "");
                } else {
                    conditionList.put("categoryName", categoryName);
                    conditionMap.put("categoryName", categoryName);
                }
                viewModel.getSupplierMapModel(conditionMap);
                viewModel.getSupplierListModel(conditionList, false);
            }
        });
        pickTypePopWindow.setOnDisMissClick(() -> {
            if (categoryName.equals("全部") || categoryName.equals("") || null == categoryName) {
                binding.tvType.contentSelect(false, false);
            } else {
                binding.tvType.contentSelect(true, false);
            }
        });

        //距离
        pickDistancePopWindow = new EnterprisePopWindow(getActivity());
        pickDistancePopWindow.setBgView(binding.grayLayout);
        pickDistancePopWindow.setOnResultClick(new BasePopWindow.OnResultClick() {
            @Override
            public void result(Object key1, Object key2, Object key3) {
                distance = (String) key1;
                conditionList.put("distance", distance);
                 distanceTemp = (String) key2;
                if ("不限".equals(distanceTemp)) {
                    conditionMap.put("distance", "10000000");
                } else {
                    conditionMap.put("distance", (String) ((String) key2).replace("KM", ""));
                }
                viewModel.getSupplierMapModel(conditionMap);
                viewModel.getSupplierListModel(conditionList, false);
            }
        });

        pickDistancePopWindow.setOnDisMissClick(() -> {
            if (distanceTemp.equals("不限") || distanceTemp.equals("") || null == distanceTemp) {
                binding.tvDistance.contentSelect(false, false);
            } else {
                binding.tvDistance.contentSelect(true, false);
            }
        });

        searchText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                conditionMap.put("name", searchText.getText().toString());
                conditionList.put("name", searchText.getText().toString());
            }
        });

    }

    private void init() {
        conditionList = new HashMap();
        conditionMap = new HashMap();
        conditionMap.put("distance", "10000000");
        conditionList.put("distance", "10000000");
        conditionList.put("name", "");
        conditionMap.put("name", "");
        viewModel.getDistanceModel();
//        viewModel.getSupplierSortModel();
        searchText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH || (keyEvent != null && keyEvent.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                    conditionMap.put("name", searchText.getText().toString());
                    conditionMap.put("latitude", currentLat);
                    conditionMap.put("longitude", currentLong);

                    conditionList.put("name", searchText.getText().toString());
                    conditionList.put("latitude", currentLat);
                    conditionList.put("longitude", currentLong);
                    viewModel.getSupplierListModel(conditionList, false);
                    return true;
                }
                return false;
            }
        });
    }

    private void initMap(Bundle savedInstanceState) {
        MapView mMapView = binding.mapView;
        mapMarkerTools.init(savedInstanceState, mMapView);
        mapMarkerTools.setMarkerClick(new MapMarkerTools.MarkerClick() {
            @Override
            public void onMarkerClick(int pos, String title) {
                showMarkerView(pos, title);
            }

            @Override
            public void onLocationChanged(Double Lat, Double Log, String address) {
                if (currentLat == null || currentLat <= 0) {
                    currentLat = Lat;
                    currentLong = Log;
                    //设置经纬度以查询地图模式下的数据
                    conditionMap.put("latitude", currentLat);
                    conditionMap.put("longitude", currentLong);
                    conditionList.put("latitude", currentLat);
                    conditionList.put("longitude", currentLong);

                    viewModel.getSupplierListModel(conditionList, false);
                    viewModel.getSupplierMapModel(conditionMap);
                    cameraToPosition();
                }
            }
        });
    }

    private void showMarkerView(int pos, String title) {
        SupplierRecommendEntity entity = bundles.get(Integer.valueOf(title));
        MapInfoWindow4 mapInfoWindow = new MapInfoWindow4(getActivity());
        mapInfoWindow.setData(entity);

        new MapInfoDialog4(getActivity(), null)
                .setDialogClickCallBack(new MapInfoDialog4.DialogClickCallBack() {
                    @Override
                    public void onClickShop(String shopId) {
                        if (TextUtils.isEmpty(shopId)) {
                            ToastUtil.show(getContext(), "企业店铺id不能为空");
                            return;
                        }
                        ShopInfoForCompanyTradesActivity.startAct(getActivity(), shopId, "", 0, 0);
                    }
                })
                .setData(mapInfoWindow.getData()).show();
    }


    public void showList(List<SupplierRecommendEntity> datas, boolean isLoadMore) {
        if (isLoadMore) {
            binding.rlvList.loadMoreComplete();
            if (datas.size() != 0) {
                supplierRecommendAdapter.addDatas(datas);
            }
        } else {
            if (datas.size() == 0) {
                binding.emptyView.setVisibility(View.VISIBLE);
            } else {
                binding.emptyView.setVisibility(View.GONE);
            }
            binding.rlvList.refreshComplete();
            binding.rlvList.setLoadingMoreEnabled(true);
            supplierRecommendAdapter.setDatas(datas);
        }
    }

//    public void showLocation(MapLongAndLatEntity mapLongAndLatEntity) {
//        if (mapLongAndLatEntity != null) {
//            currentLat = Double.valueOf(mapLongAndLatEntity.getLat());
//            currentLong = Double.valueOf(mapLongAndLatEntity.getLng());
//
//            //设置经纬度以查询地图模式下的数据
//            conditionMap.put("latitude", currentLat);
//            conditionMap.put("longitude", currentLong);
//            viewModel.getSupplierMapModel(conditionMap);
//
//            cameraToPosition();
//        }
//    }

    public void showCityPopWindow(List<DictEntity3> data) {
        this.cityDictEntityList = data;
        if (cityDictEntityList != null && cityDictEntityList.size() > 0) {
            currentLat = Double.valueOf(data.get(0).getLatitude());
            currentLong = Double.valueOf(data.get(0).getLongitude());
            conditionMap.put("cityNo", data.get(0).getId());
            //设置经纬度以查询地图模式下的数据
            conditionMap.put("latitude", currentLat);
            conditionMap.put("longitude", currentLong);

            conditionList.put("cityNo", data.get(0).getId());
            //设置经纬度以查询地图模式下的数据
            conditionList.put("latitude", currentLat);
            conditionList.put("longitude", currentLong);
            viewModel.getSupplierListModel(conditionList, false);
            viewModel.getSupplierMapModel(conditionMap);
            cameraToPosition();
        }
        supplierCityWindow3.setData(data);
    }

    public void showDistancePopWindow(List<DictEntity3> data) {
        setSecondDistanceDatas(data);
//        if (data != null && data.size() > 0) {
//            //未选择距离时设置一个最大默认距离
//            conditionMap.put("distance", data.get(data.size() - 1).getName().replaceAll("KM", ""));
//            conditionList.put("distance", data.get(data.size() - 1).getId());
//            viewModel.getSupplierMapModel(conditionMap);
//            viewModel.getSupplierListModel(conditionList, false);
//        }
        pickDistancePopWindow.setData(distanceDatas);
    }

//    public void showSortPopWindow(List<DictEntity3> data) {
//        supplierSortWindow3.setData(data);
//    }

    public void showTypePopWindow(List<DictEntity3> data) {
        supplierTypeWindow3.setData(data);
    }

    public void showMap(List<SupplierRecommendEntity> datas) {
        mapSupplierList = datas;
        addMarkInfoWindow(mapSupplierList);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.right_view_location://定位
                Intent intent = new Intent();
                intent.setClass(getActivity(), SelectAddressActivity.class);
                intent.putExtra(SelectAddressActivity.TITLE, "选择定位地址");
                intent.putExtra(SelectAddressActivity.LATITUDE, currentLat);
                intent.putExtra(SelectAddressActivity.LONGTITUDE, currentLong);
                startActivityForResult(intent, 101);
                break;
            case R.id.right_view://列表和地图切换
                if (binding.rightView.getText().toString().equals(TYPE_MAP)) {
                    binding.rightView.setText(TYPE_LIST);
                    binding.listLayout.setVisibility(View.GONE);
                    binding.mapView.setVisibility(View.VISIBLE);
                    binding.rightViewLocation.setVisibility(View.VISIBLE);
                    //binding.sortView.setVisibility(View.GONE);
                } else {
                    binding.rightView.setText(TYPE_MAP);
                    binding.listLayout.setVisibility(View.VISIBLE);
                    binding.mapView.setVisibility(View.GONE);
                    binding.rightViewLocation.setVisibility(View.VISIBLE);
                    //binding.sortView.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.tv_type://商品分类筛选
                binding.tvType.contentSelect(false, true);
                showTypePopWindow();
                break;
            case R.id.tv_distance://距离筛选
                binding.tvDistance.contentSelect(false, true);
                showDistancePopWindow();
                if (distanceDatas == null) {
                    viewModel.getDistanceModel();
                }
                break;
            case R.id.img_back_top://滚动到顶部
                binding.rlvList.smoothScrollToPosition(0);
                break;
            case R.id.search_tv:
/*                if (TextUtils.isEmpty(conditionMap.get("name").toString()) || TextUtils.isEmpty(conditionList.get("name").toString())) {
                    MToast.showToast(getContext(), "请输入供应商");
                    return;
                }*/
                viewModel.getSupplierListModel(conditionList, false);
                viewModel.getSupplierMapModel(conditionMap);
                break;

        }
    }

    private void addMarkInfoWindow(List<SupplierRecommendEntity> datas) {
        try {
            mapMarkerTools.mapClear();
            bundles.clear();
            for (int i = 0; i < datas.size(); i++) {
                if (null != datas && datas.size() > 0) {
                    SupplierRecommendEntity entity = datas.get(i);
                    if (null != entity && !TextUtils.isEmpty(entity.getLatitude()) && !TextUtils.isEmpty(entity.getLongitude())) {
                        double currentLat = Double.parseDouble(entity.getLatitude());
                        double currentLong = Double.parseDouble(entity.getLongitude());
                        if (currentLat == 0 || currentLong == 0) {
                            return;
                        }
                        mapMarkerTools.addPoiItem(currentLat, currentLong, "");
                        bundles.add(datas.get(i));
                    }
                }
            }
            mapMarkerTools.addAllMarkerToMap(R.mipmap.ic_map_overlay, false);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //设置定位点
    private void cameraToPosition() {
        mapMarkerTools.setMyLocation(currentLat, currentLong);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 101 && data != null) {
            currentLat = data.getDoubleExtra(SelectAddressActivity.LATITUDE, 0);
            currentLong = data.getDoubleExtra(SelectAddressActivity.LONGTITUDE, 0);
            conditionMap.put("latitude", currentLat);
            conditionMap.put("longitude", currentLong);
            conditionList.put("latitude", currentLat);
            conditionList.put("longitude", currentLong);
            viewModel.getSupplierListModel(conditionList, false);

            //设置经纬度以查询地图模式下的数据
            viewModel.getSupplierMapModel(conditionMap);

            cameraToPosition();
        }
    }

    private void setSecondTypeDatas(List<MenuEntity> data) {
        List<PickSelectEntity> types = new ArrayList<>();
        if (data != null) {
            for (MenuEntity entity : data) {
                PickSelectEntity pickSelectEntity = new PickSelectEntity();
                pickSelectEntity.setNo(entity.getId());
                pickSelectEntity.setProjectscale(entity.getName());
                types.add(pickSelectEntity);
            }
        }
        typeDatas.clear();
        typeDatas.addAll(types);
    }

    private void setSecondDistanceDatas(List<DictEntity3> data) {
        List<PickSelectEntity> types = new ArrayList<>();
        if (data != null) {
            for (DictEntity3 entity : data) {
                PickSelectEntity pickSelectEntity = new PickSelectEntity();
                pickSelectEntity.setNo(entity.getId());
                pickSelectEntity.setProjectscale(entity.getName());
                types.add(pickSelectEntity);
            }
        }
        distanceDatas.clear();
        PickSelectEntity pickSelectEntity = new PickSelectEntity();
        pickSelectEntity.setProjectscale("不限");
        pickSelectEntity.setNo("10000000");
        types.add(0, pickSelectEntity);
        distanceDatas.addAll(types);
    }

    private void showTypePopWindow() {
        pickTypePopWindow.showPopwindowGoods(binding.llBg);
        pickTypePopWindow.setData(typeDatas);
    }

    private void showDistancePopWindow() {
        pickDistancePopWindow.showPopwindowGoods(binding.llBg);
        pickDistancePopWindow.setData(distanceDatas);
    }

    private void initPopWindow() {

    }
}